//
//  MainAntistopVC_V4.m
//  ZITHER
//
//  Created by weixin on 2018/11/19.
//  Copyright © 2018 weixn. All rights reserved.
//

#import "MainAntistopVC_V4.h"
#import "MainSearchBottom.h"
#import "MainDefaulSearctVC.h"
#import "Seach_SearchResult_VC_WX.h"


@interface MainAntistopVC_V4 ()<UITextViewDelegate,UITextFieldDelegate>

@property (nonatomic,strong)BaseLab *placeholderLab;//输入手机号提示

@property (nonatomic,strong)UITextView *textView;

@property (nonatomic,strong)BaseLab *tipe;//输入手机号提示

@property (nonatomic,strong)MainSearchBottom *bottomView;

@property (nonatomic,strong)NSMutableArray * arrM;

@end

@implementation MainAntistopVC_V4

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setNav];
    
    [self setUI];
    
    [self loadKeyWord];
    
    //监听键盘，键盘出现
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(keyboardwill:)
                                                name:UIKeyboardWillShowNotification object:nil];

    //监听键盘
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(keybaordhide:)
                                                name:UIKeyboardWillHideNotification object:nil];
    
}

-(void)loadAttribute{
    [[serviceDefualt loadSearchAttribute:nil]subscribeNext:^(ResponseData* x) {
        if (x.success) {
            [kUSER_Filtrate_MANAGER resetData];
            NSArray *arrData = x.responseRawData[@"data"];
            NSMutableArray *arrM = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in arrData) {
                Seach_FiltrateAttribute_Model_WX *model = [Seach_FiltrateAttribute_Model_WX yy_modelWithDictionary:dic];
                if ([model.name isEqualToString:@"品牌"]) {
                    [arrM insertObject:model atIndex:0];
                }else if ([model.name isEqualToString:@"价格"]){
                    Seach_FiltrateAttributeSub_Model_WX *modelChild = model.child[1];
                    for (Seach_FiltrateAttributeSubData_Model_WX *modelData in modelChild.data) {
                        modelData.ispublicPrice = YES;
                    }
                    [arrM addObject:model];
                }else{
                    [arrM addObject:model];
                }
            }
            kUSER_Filtrate_MANAGER.arrAttribute = arrM;
        }else{
            [Tools showTips:x.errorInfo];
        }
        
    }];
}
-(void)setNav{
    
    [self.baseNavigationView setHiddenNav:NO VC:self];
    /* TODO: ================= 导航栏V4样式 =================*/
    [self.baseNavigationView NavigationBarStyle:1];
    self.baseNavigationView.navViewStyle.title.text = @"关键词寻表";
    self.baseNavigationView.navViewStyle.leftBtn.hidden = YES;
    self.baseNavigationView.leftButton1.hidden = YES;
//    self.baseNavigationView.navViewStyle.isShowShadow = NO;
//    self.baseNavigationView.bottomLineView.hidden = YES;
    //登录或注册

}

-(void)setUI{
    
    [self.view addSubview:self.textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(40+NaviHeight);
        make.left.mas_equalTo(12);
        make.width.mas_equalTo(kScreenW-20);
        make.height.mas_equalTo(40);
    }];
    
    [self.view addSubview:self.placeholderLab];
    [self.placeholderLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.textView.mas_bottom).offset(-5);
        make.left.equalTo(self.view).offset(12);
    }];
    
    [self.view addSubview:self.tipe];
    [self.tipe mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_bottom).offset(10);
        make.left.equalTo(self.view).offset(15);
    }];
    [self.view addSubview:self.bottomView];
    [self.textView becomeFirstResponder];
}

- (UITextView *)textView{
    if (!_textView) {
        _textView = [[UITextView alloc]init];
        _textView.font = [UIFont systemFontOfSize:12];
        _textView.delegate = self;
        _textView.layer.cornerRadius = 5;
        _textView.enablesReturnKeyAutomatically = YES;
        _textView.tintColor = baseColorLight;
//        _textView.keyboardType = UIKeyboardTypeNumberPad;
        _textView.qmui_borderPosition = QMUIViewBorderPositionBottom;
        _textView.qmui_borderWidth = 1;
        _textView.qmui_borderColor = baseColorLight;
//        _textView.keyboardAppearance = UIKeyboardAppearanceDark;
        _textView.font = [UIFont fontWithName:@"PingFangSC-Medium" size:28];
        // 限制可输入的字符长度
        _textView.maximumZoomScale = 8;//设置最大缩放
        _textView.returnKeyType = UIReturnKeyDone;
    }
    return _textView;
}

- (void)textViewDidChange:(UITextView *)textView
{
//    if (textView.text.length > 11)
//    {
//        textView.text = [textView.text substringToIndex:11];
//    }
    //记录输入的字数，你若不统计字数，忽略这行
    //    self.limitWordLable.text = [NSString stringWithFormat:@"%lu/%d", (unsigned long)[textView.text length], 200];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([text isEqualToString:@"\n"]) {
        [self done];
        return NO;
    }
    
    self.placeholderLab.hidden = YES;
    /** 限制字数 10个 */
    NSString *str = [NSString stringWithFormat:@"%@%@", textView.text, text];
    if (str.length>0) {
//        self.codeBtn.alpha = 1;
    }else{
//        self.codeBtn.alpha = 0.4;
    }
//    if (str.length > 11)
//    {
//        NSRange rangeIndex = [str rangeOfComposedCharacterSequenceAtIndex:11];
//
//        if (rangeIndex.length == 1)//字数超限
//        {
//            textView.text = [str substringToIndex:11];
//        }else{
//            NSRange rangeRange = [str rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 11)];
//            textView.text = [str substringWithRange:rangeRange];
//        }
//        return NO;
//    }
    return YES;
}


//当键盘出现时，调用此方法
-(void)keyboardwill:(NSNotification *)sender
{
    //获取键盘高度
    NSDictionary *dict=[sender userInfo];
    NSValue *value=[dict objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardrect = [value CGRectValue];
    int height=keyboardrect.size.height;

    [UIView animateWithDuration:0.3 animations:^{
        self.bottomView.frame = CGRectMake(0, kScreenH-50-height, kScreenW, 50);
    }];
    
}

//当键盘时候，视图回到原定
-(void)keybaordhide:(NSNotification *)sender
{
    [UIView animateWithDuration:0.3 animations:^{
        self.bottomView.frame = CGRectMake(0, kScreenH-50, kScreenW, 50);
    }];
}


-(BaseLab *)placeholderLab{
    if (!_placeholderLab) {
        _placeholderLab = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@"请输入品牌系列型号" font:20 textColor:[UIColor colorWithHex:@"333333"] isBold:NO numberOfLines:0];
        _placeholderLab.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:20];
    }
    return _placeholderLab;
}

-(BaseLab *)tipe{
    if (!_tipe) {
        _tipe = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@"热门搜索" font:20 textColor:[UIColor colorWithHex:@"333333"] isBold:NO numberOfLines:0];
        
        _tipe.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];

    }
    return _tipe;
}

-(MainSearchBottom *)bottomView{
    if (!_bottomView) {
        _bottomView = [[MainSearchBottom alloc]initWithFrame:CGRectMake(0, kScreenH-50, kScreenW, 50)];
        _bottomView.backgroundColor = [UIColor colorWithHex:@"969696"];
        
        @weakify(self);
        [[_bottomView.btnCancel rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [[_bottomView.btnDone rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [kUSER_Filtrate_MANAGER resetData];
            [self done];
         
        }];
    }
    return _bottomView;
}


-(void)done{
    kUSER_Filtrate_MANAGER.SearchResultTopBarModel.keyWord = self.textView.text;

    if (self.indexType == 1) {
        if (self.block) {
            self.block(self.textView.text);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        /** 关键词搜索 */
//        MainDefaulSearctVC * vc = [[MainDefaulSearctVC alloc]init];
//        vc.indexType = 0;
//        vc.keyWord = self.textView.text;
//        [self.navigationController pushViewController:vc animated:YES];
        if (kUSER_Filtrate_MANAGER.arrAttribute.count>0) {
            Seach_SearchResult_VC_WX *vc = [[Seach_SearchResult_VC_WX alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [Tools showTips:@"数据错误，无法跳转"];
        }
    }
}

-(void)loadKeyWord{
    [[serviceDefualt loadkeywordlist:nil]subscribeNext:^(ResponseData * x) {
        if (x.success) {
            //拿到keyword 搜索
            self.arrM = [[NSMutableArray alloc]initWithArray:x.responseRawData[@"data"]];
            [self createKeyWordUI];
            [self.view addSubview:self.bottomView];
        }
    }];
    if (self.indexType != 1) {
        [self loadAttribute];
    }
    
}

-(void)createKeyWordUI{
    BaseBtn * lastBtn = nil;
    for (int i = 0; i<self.arrM.count; i++) {
        BaseBtn *btn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 0, 0) NormalText:self.arrM[i][@"keyword"] NormalTextColor:[UIColor colorWithHex:@"333333"] SeleText:@"" SeleTextColor:nil font:13 isBold:NO];
        btn.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:13];
        [btn setBorderWithColor:HexColor(0xdedede) width:1];
        [btn setCornerRadiusWithRadius:2 isMasks:YES];
        btn.tag = 100+i;
        @weakify(self);
        [[btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            if (self.indexType == 1) {
                if (self.block) {
                    self.block(self.arrM[btn.tag-100][@"keyword"]);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                /** 关键词搜索 */
//                MainDefaulSearctVC * vc = [[MainDefaulSearctVC alloc]init];
//                vc.indexType = 0;
//                vc.keyWord = self.arrM[btn.tag-100][@"keyword"];
//                [self.navigationController pushViewController:vc animated:YES];
                kUSER_Filtrate_MANAGER.SearchResultTopBarModel.keyWord = self.arrM[btn.tag-100][@"keyword"];
                if (kUSER_Filtrate_MANAGER.arrAttribute.count>0) {
                    Seach_SearchResult_VC_WX *vc = [[Seach_SearchResult_VC_WX alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    [Tools showTips:@"数据错误，无法跳转"];
                }
            }
            
        }];

        
        
        
        
        
        
//        if (i == 2 || i ==3 ||i==5||i==8) {
//            [btn setTitle:@"劳力士" forState:UIControlStateNormal];
//        }
        [self.view addSubview:btn];
        
        //估算添加以后是否超过屏幕
        CGFloat width = [self getTitleSizeWidth:btn.titleLabel.text];
        CGFloat y = CGRectGetMaxX(lastBtn.frame)+10+width;
        if (lastBtn == nil) {
            //第一个
            btn.frame = CGRectMake(15,CGRectGetMaxY(self.tipe.frame)+15, width, 25 );
        }else{
       
            if (y>kScreenW-15) {
                //超出范围需要换行
                btn.frame = CGRectMake(15, CGRectGetMaxY(lastBtn.frame)+15, width, 25 );
            }else{
                //未超出宽度往后添加
                btn.frame = CGRectMake(CGRectGetMaxX(lastBtn.frame)+15, CGRectGetMaxY(lastBtn.frame)-25, width, 25 );
            }
        }
        lastBtn = btn;
    }
}


-(CGFloat)getTitleSizeWidth:(NSString*)text{
    CGSize titleSize = [text boundingRectWithSize:CGSizeMake(10000,25) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFang-SC-Regular" size:13]} context:nil].size;
    return titleSize.width+25;
}

-(void)viewWillDisappear:(BOOL)animated{
    NSArray *viewControllers = self.navigationController.viewControllers;
    if (viewControllers.count > 1 && [viewControllers objectAtIndex:viewControllers.count-2] == self) {
        // View is disappearing because a new view controller was pushed onto the stack
        NSLog(@"New view controller was pushed");
    } else if ([viewControllers indexOfObject:self] == NSNotFound) {
        
        if (self.indexType != 1) {
            // View is disappearing because it was popped from the stack
            [kUSER_Filtrate_MANAGER claenData];
        }
    }
}
@end
